package com.chixing.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 该类表示日期工具类
 * 实现了Date与字符串的相互转化
 */
public class DateUtil {
    //    年月日时分秒 ： yyyy-MM-dd HH:mm:ss  pattern
    public static final String DATE_PATTERN_YMDHMS = "yyyy-MM-dd HH:mm:ss";

    //    年月日时分：yyyy-MM-dd HH:mm
    public static final String DATE_PATTERN_YMDHM = "yyyy-MM-dd HH:mm";

    //    年月日时分：yyyy-MM-dd
    public static final String DATE_PATTERN_YMD = "yyyy-MM-dd";
    //    时分秒：HH:mm:ss
    public static final String DATE_PATTERN_HMS = "HH:mm:ss";

    //    时分：HH:mm
    public static final String DATE_PATTERN_HM = "HH:mm";
    public static String date2String(Date date,String pattern){
        DateFormat dateFormat = new SimpleDateFormat(pattern);
        String dateStr = dateFormat.format(date);
        return dateStr;
    }
    public static Date string2Date(String dateStr,String pattern){
        DateFormat dateFormat = new SimpleDateFormat(pattern);
        Date date = null;
        try {
            date = dateFormat.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static void dateComparetodate(String date1,String date2){
        Date date3 = DateUtil.string2Date(date1, DateUtil.DATE_PATTERN_YMDHMS);
        Date date4 = DateUtil.string2Date(date2, DateUtil.DATE_PATTERN_YMDHMS);
        long days = ((Math.abs(date3.getTime() - date4.getTime())) / 1000 / 24 / 60 / 60);
        long hours = (Math.abs((date3.getTime() - date4.getTime()))/ 1000 / 60 /60);
        long mintues = ((Math.abs(date3.getTime() - date4.getTime()))/1000/60);
        System.out.println("相差天：" + days);
        System.out.println("相差小时：" + hours);
        System.out.println("相差分钟：" + mintues);
    }


//    public static void main(String[] args) {
//        Date date = new Date();
//        String datestr = DateUtil.date2String(date,DateUtil.DATE_PATTERN_YMDHMS);
//        System.out.println(datestr);
//
//        String dateStr = "2021-8-9 10:11:56";
//        Date date1 =  DateUtil.string2Date(dateStr,DateUtil.DATE_PATTERN_YMDHMS);
//        System.out.println(date1);
//    }
}
